package com.gy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gy.controller.common.UploadController;
import com.gy.controller.common.UserHolder;
import com.gy.entity.Form.FormEntity;
import com.gy.enumeration.SpaceRoleEnum;
import com.gy.mapper.FormMapper;
import com.gy.result.Result;
import com.gy.service.FormService;
import com.gy.service.UserService;
import com.gy.vo.form.AddMemberVO;
import com.gy.vo.form.FormMemberVO;
import com.gy.vo.form.MemberVO;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class FormServiceImpl extends ServiceImpl<FormMapper, FormEntity> implements FormService {
    @Autowired
    private UploadController uploadController;
    @Autowired
    private UserService userService;
    @Resource
    private FormMapper formMapper;
    @Override
    public FormEntity getFormsByUserId(Long formId) {
        return lambdaQuery()
                .select(FormEntity::getId,
                        FormEntity::getRuleBuild,
                        FormEntity::getName,
                        FormEntity::getOptionBuild,
                        FormEntity::getFormData,
                        FormEntity::getCreatedAt,
                        FormEntity::getPdfPath,
                        FormEntity::getCreator)
                .eq(FormEntity::getId, formId)
                .one();
    }


    /**
     * 分页获取用户的表单数据
     * @param page
     * @param size
     * @return
     */
    @Override
    public IPage<FormEntity> getFormsByUserIdPaged(int page, int size) {
        Long userId = UserHolder.getUser().getUserId();
        Page<FormEntity> formPage = new Page<>(page, size);
        return formMapper.selectFormsByUserIdPaged(userId, formPage);
    }



    @Override
    @Transactional
    public Result saveForm(FormEntity form) {

        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return Result.error("用户未登录或用户ID为空");
        }

        try {
            // 获取用户的昵称
            String creator = userService.getUserNameByUserId(userId);
            if (creator == null) {
                return Result.error("用户不存在");
            }
            form.setCreator(creator);

            // 生成 UUID 并设置到 name 字段
            String randomName = UUID.randomUUID().toString();
            form.setName(randomName);

            // 保存表单
            save(form);

            // 新增到用户和表单关联表
            formMapper.saveMember(form.getId(), userId);

            return Result.success("表单保存成功！");
        } catch (Exception e) {
            // 捕获异常并返回错误信息
            return Result.error("表单保存失败：" + e.getMessage());
        }
    }


    @Override
    public Result deleteForm(Long id) {
        // 获取当前用户ID
        Long userId = UserHolder.getUser().getUserId();

        // 获取表单信息
        FormEntity form = getById(id);

        // 检查表单是否存在
        if (form == null) {
            return Result.error("表单不存在");
        }

        // 检查用户权限
//        if (!form.getUserId().equals(userId)) {
//            return Result.error("无权限删除此表单");
//        }

        // 获取PDF路径并删除文件
        String pdfPath = form.getPdfPath();
        if (pdfPath != null && !pdfPath.isEmpty()) {
            try {
                uploadController.deleteFile(pdfPath);
            } catch (Exception e) {
                log.error("删除文件失败, pdfPath: " + pdfPath, e);
                return Result.error("删除文件失败");
            }
        } else {
            log.warn("pdfPath 为空，无需删除文件");
        }

        // 删除表单
        boolean success = removeById(id);
        if (success) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    @Override
    public Result<AddMemberVO> addMember(Long id, Long userId) {
        //查看是否存在该用户
        if (!userService.isUserExist(userId)) {
            return Result.error("用户不存在");
        }
        try {
            Boolean b = formMapper.addMember(id, userId);
            //根据用户id查询用户信息
           AddMemberVO userPersonalInfo = userService.getUserPersonalInfo(userId);
            if (b) {
                return Result.success(userPersonalInfo);
            } else {
                return Result.error("用户添加失败");
            }
        } catch (DuplicateKeyException e) {
            return Result.error("不能重复添加用户");
        } catch (Exception e) {
            return Result.error("添加用户时发生未知错误: " + e.getMessage());
        }
    }

    @Override
    public Result<List<FormMemberVO>> listMembers(Long id) {
        List<MemberVO> memberVOS = formMapper.listMembers(id);

        List<FormMemberVO> formMemberVOS = new ArrayList<>();
        for (MemberVO memberVO : memberVOS) {
            FormMemberVO formMemberVO = new FormMemberVO();
            formMemberVO.setFormRole(memberVO.getFormRole());

            // 根据用户id批量查询用户的昵称和头像
            Long userId = memberVO.getUserId();
            formMemberVO.setUserId(userId);
            String nickName = userService.getUserNameByUserId(userId);
            formMemberVO.setNickName(nickName);
            formMemberVO.setCreateTime(memberVO.getCreateTime());
            String avatar = userService.getUserAvatarByUserId(userId);
            if (avatar != null && !avatar.isEmpty()) {
                formMemberVO.setAvatar(avatar);
            } else {
                formMemberVO.setAvatar("default_avatar_url"); // 设置默认头像URL
            }

            formMemberVOS.add(formMemberVO);
        }

        return Result.success(formMemberVOS);
    }

    @Override
    public Result deleteMember(Long id, Long userId) {
        try {
            Boolean isDeleted = formMapper.deleteMember(id, userId);
            if (isDeleted) {
                return Result.success(isDeleted);
            } else {
                return Result.error("成员未找到");
            }
        } catch (Exception e) {
            return Result.error("删除成员时发生错误");
        }
    }

    @Override
    public Result updateMemberRole(Long id, Long userId, String role) {
        try{
            Boolean isUpdated =formMapper.updateRole(id, userId, role);
            if (isUpdated) {
                return Result.success(isUpdated);
            } else {
                return Result.error("更新角色失败，请联系管理员");
            }
        }catch (Exception e) {
            return Result.error("更新成员角色时发生错误");
        }


    }

    @Override
    public Result updateFromById(FormEntity form) {

        try {
            // 更新表单
            int updateResult = formMapper.updateById(form);
            if (updateResult > 0) {
                return Result.success("表单更新成功！");
            } else {
                return Result.error("表单更新失败，未找到对应记录");
            }
        } catch (Exception e) {
            // 捕获异常并返回错误信息
            return Result.error("表单更新失败：" + e.getMessage());
        }
    }



}
